package com.tomecode.tools.maven.settings.config;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;

import com.tomecode.tools.maven.settings.parser.XmlFactory;

/**
 * configuration for maven-settings-editor
 * 
 * @author Tomas Frastia
 * @see http://www.tomecode.com or
 *      http://code.google.com/p/maven-settings-editor/
 * 
 */
public final class Configuration {

	private static final File CONFIG_FILE = new File(System.getProperty("osgi.configuration.area") + File.separator + "maven-settings-editor.xml");

	private Configuration() {

	}

	public static final List<Maven> loadMavens() {
		List<Maven> mavens = new ArrayList<Maven>();
		if (CONFIG_FILE.exists()) {
			parseFile(CONFIG_FILE, mavens);
		}
		return mavens;
	}

	private static final void parseFile(File file, List<Maven> mavens) {
		try {

			Element rootElement = XmlFactory.parse(file).getRootElement();
			if (rootElement != null) {
				if ("maven-settings-editor".equalsIgnoreCase(rootElement.getName())) {
					parseMavens(rootElement.element("mavens"), mavens);
				}
			}

		} catch (Exception e) {
		}
	}

	private static final void parseMavens(Element element, List<Maven> mavens) {
		if (element != null) {
			List<?> list = element.elements("maven");
			if (list != null) {
				for (Object o : list) {
					Element eMaven = (Element) o;
					Maven maven = new Maven();
					maven.setHome(eMaven.elementTextTrim("home"));
					maven.setRepository(eMaven.elementTextTrim("repo"));
					maven.setActive(eMaven.elementTextTrim("active"));
					maven.setVersion(eMaven.elementTextTrim("version"));
					mavens.add(maven);
				}
			}
		}
	}

	public final static void saveMavens(List<Maven> mavens) {
		Document document = XmlFactory.newDocument();
		Element eRoot = DocumentFactory.getInstance().createElement("maven-settings-editor");
		document.setRootElement(eRoot);
		Element eMavens = DocumentFactory.getInstance().createElement("mavens");
		eRoot.add(eMavens);

		for (Maven maven : mavens) {
			Element eMaven = DocumentFactory.getInstance().createElement("maven");
			eMavens.add(eMaven);

			eMaven.add(XmlFactory.createElement("active", String.valueOf(maven.isActive()), null));
			eMaven.add(XmlFactory.createElement("version", maven.getVersion().getName(), null));
			eMaven.add(XmlFactory.createElement("home", maven.getHome().getPath(), null));
			eMaven.add(XmlFactory.createElement("repo", maven.getRepository().getPath(), null));
		}

		XmlFactory.xmlToFile(document, CONFIG_FILE);
	}
}
